<template>
    <div class="my-tag">
        <input 
            v-if="isEdit"
            v-focus
            ref="inp"
            class="input"
            type="text"
            placeholder="输入标签"
            :value="value"
            @blur="isEdit=false"
            @keyup.enter="handleEnter"
            
        />
        <div 
            v-else 
            @dblclick="handleClick"
            class="text">
            {{value}}
        </div>
    </div>
</template>

<script>
export default {
    name: 'MyTag',
    props: {
        value: String
    },
    data() {
        return {
            isEdit: false
        }
    },
    methods: {
        handleClick() {
            //双击后 切换到编辑状态
            this.isEdit = true
            
            //立刻获取焦点 nextTick
            //可以这样写 用指令也可以实现
            //这里用v-focus
            //this.$nextTick(() => {
            //    this.$refs.inp.focus()
            //})
        },
        handleEnter(e) {
            if(e.target.value.trim() === '') {
                alert('请输入文字')
                return
            }

            //子传父，将回车时，输入框的内容提交给父组件更新
            //由于父组件是v-model，触发事件，需要触发 input 事件
            console.log('from e:', e.target.value)
            console.log('from $refs:', this.$refs.inp.value)
            //两种方法都可以获取数据
            this.$emit('input', e.target.value)
            //this.$emit('input', this.$refs.inp.value)

            //提交完成 关闭输入状态
            this.isEdit = false
        }
    }
}
</script>

<style lange="less" scoped>
.my-tag {
    cursor: pointer;

    .input {
        appearance: none;
        outline: none;
        border: 1px solid #ccc;
        width: 100px;
        height: 40px;
        box-sizing: border-box;
        padding: 10px;
        color: #666;

        &::placeholder {
            color: #666;
        }
    }
}
</style>